const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[month, day].map(formatNumber).join('-')} ${[hour, minute].map(formatNumber).join(':')}`
}


const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function filter(str) { // 特殊字符转义
  str += ''; // 隐式转换
  str = str.replace(/%/g, '%25');
  str = str.replace(/\+/g, '%2B');
  str = str.replace(/ /g, '%20');
  str = str.replace(/\//g, '%2F');
  str = str.replace(/\?/g, '%3F');
  str = str.replace(/&/g, '%26');
  str = str.replace(/\=/g, '%3D');
  str = str.replace(/#/g, '%23');
  return str;
}

function formateObjToParamStr(paramObj) {
  const sdata = [];
  for (let attr in paramObj) {
    sdata.push(`${attr}=${filter(paramObj[attr])}`);
  }
  return sdata.join('&');
};

function fillAll(obj, isProvide = false) {
  let res = false;
  if (obj) {
    const values = Object.values(obj);
    res = values.every(it => {
      return !!it
    })
    if (isProvide) {
      showFormNotFillError(res);
    }
  } else {
    console.error('params is not Object:', typeof obj)
  }
  return res;
}

function showFormNotFillError(validResult = true) {
  if (!validResult) {
    wx.showToast({
      title: '表单存在未填项',
      icon: 'none'
    })
    return
  }
}

function logout() {
  wx.removeStorageSync('auth');
  wx.removeStorageSync('root');
  const app = getApp();
  app.globalData.prevPage = null;
  app.globalData.root = null;
  wx.reLaunch({
    url: '../login/login',
  })
}
module.exports = {
  formatTime,
  formateObjToParamStr,
  fillAll,
  logout
}